package com.yfree.application;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.StrictMode;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.tencent.smtt.sdk.QbSdk;
import com.yfree.YConfig;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.bitmap.core.BitmapDisplayConfig;
import net.tsz.afinal.bitmap.display.Displayer;

import java.security.KeyStore;

/*
                        佛曰:
                             写字楼里写字间，写字间里程序员；
                             程序人员写程序，又拿程序换酒钱。
                             酒醒只在网上坐，酒醉还来网下眠；
                             酒醉酒醒日复日，网上网下年复年。
                             但愿老死电脑间，不愿鞠躬老板前；
                             奔驰宝马贵者趣，公交自行程序员。
                             别人笑我忒疯癫，我笑自己命太贱；
                             不见满街漂亮妹，哪个归得程序员？
           <佛祖保佑>                                            <永无BUG>
                                       _ooOoo_
                                      o8888888o
                                      88" . "88
                                      (| -_- |)
                                      O\  =  /O
                                   ____/`---'\____
                                 .'  \\|     |//  `.
                                /  \\|||  :  |||//  \
                               /  _||||| -:- |||||-  \
                               |   | \\\  -  /// |   |
                               | \_|  ''\---/''  |   |
                               \  .-\__  `-`  ___/-. /
                             ___`. .'  /--.--\  `. . __
                          ."" '<  `.___\_<|>_/___.'  >'"".
                         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
                         \  \ `-.   \_ __\ /__ _/   .-` /  /
                    ======`-.____`-.___\_____/___.-`____.-'======
                                       `=---='
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
           <佛祖镇楼>                                             <BUG辟易>
*/
public abstract class YApplication extends YMultiDexApplication {
    private static FinalHttp finalHttp;
    private static FinalBitmap finalBitmap;
    protected static Context applicationContext;

    private boolean shouldInit() {
        for (ActivityManager.RunningAppProcessInfo info : ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses())
            if (info.pid == android.os.Process.myPid() && getPackageName().equals(info.processName))
                return true;
        return false;
    }

    @Override
    final public void onCreate() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
            QbSdk.initX5Environment(applicationContext, null);
        if (shouldInit()) {
            onYConfig();
            super.onCreate();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build());
            }
            applicationContext = getApplicationContext();
            onYOnceCreated();
        }
        onYCreated();
    }

    protected abstract void onYConfig();

    protected void onYOnceCreated() {
    }

    protected abstract void onYCreated();

    synchronized public static FinalHttp getFinalHttp() {
        if (finalHttp == null) {
            finalHttp = new FinalHttp();
        }
        finalHttp.configRequestExecutionRetryCount(10);
        if (YConfig.IP != null && YConfig.IP.startsWith("https://")) {
            try {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
                YSSLSocketFactory sf = new YSSLSocketFactory(trustStore);
                sf.setHostnameVerifier(YSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                finalHttp.configSSLSocketFactory(sf);
            } catch (Exception ignored) {
            }
        }
        finalHttp.configTimeout(YConfig.yPostTimeOut);
        if (YConfig.onYHTTPHeader != null) {
            YConfig.onYHTTPHeader.onYHTTPHeader(finalHttp);
        }
        return finalHttp;
    }

    public static FinalBitmap getFinalBitmap() {
        if (finalBitmap == null) {
            finalBitmap = FinalBitmap.create(applicationContext);
            //finalBitmap.configBitmapLoadThreadSize(10);// 定义线程数量
            finalBitmap.configDiskCachePath(applicationContext.getCacheDir()
                    + "/YFBCache"
                    + YConfig.FINALBITMAPCACHEDIR);// 设置缓存目录
            finalBitmap.configDiskCacheSize(1024 * 1024 * 100);// 设置缓存大小
            // finalBitmap.configMemoryCacheSize((int)
            // (Runtime.getRuntime().maxMemory() / 8));
            if (YConfig.isSetPicDefault) {
                finalBitmap.configLoadfailImage(YConfig.loadingFailImage);
                finalBitmap.configLoadingImage(YConfig.loadingImage);
            }
            finalBitmap.configDisplayer(new Displayer() {
                @Override
                public void loadFailDisplay(View view, Bitmap bitmap) {
                    if (bitmap == null) {
                        return;
                    }
                    ImageView imageView = (ImageView) view;
                    imageView.setScaleType(ScaleType.FIT_CENTER);
                    imageView.setImageBitmap(bitmap);
                    startAnim(imageView);
                }

                @Override
                public void loadCompletedisplay(View view, Bitmap bitmap, BitmapDisplayConfig config) {
                    ImageView imageView = (ImageView) view;
                    imageView.setImageBitmap(bitmap);
                    startAnim(imageView);
                }

                private void startAnim(ImageView imageView) {
                    AnimationSet animationSet = new AnimationSet(true);
                    animationSet.setDuration(500);
                    animationSet.setFillAfter(true);
                    animationSet.addAnimation(new AlphaAnimation(0, 1));
                    // animationSet.addAnimation(new ScaleAnimation(0, 1, 0, 1,
                    // imageView.getWidth() / 2, imageView.getHeight() / 2));
                    imageView.startAnimation(animationSet);
                }
            });
            finalBitmap.configRecycleImmediately(true);
//            finalBitmap.setExitTasksEarly(true);
        }
        return finalBitmap;
    }

    @Override
    public void onTrimMemory(int level) {
        cleanMemory();
        super.onTrimMemory(level);
    }

    public void cleanMemory() {
        System.gc();
        System.runFinalization();
    }
}
